import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// 模拟API调用
const mockRegistrationOrders = [
  {
    id: 'R001',
    patientName: '王*柯',
    department: '内科',
    doctorName: '张医生',
    appointmentDate: '2024-01-15',
    appointmentTime: '09:00',
    status: '已完成',
    fee: 50,
    registrationNo: '20240115001',
    symptoms: '感冒，发热38.5度',
    diagnosis: '上呼吸道感染',
    treatment: '对症治疗，多休息'
  },
  {
    id: 'R002',
    patientName: '王*柯',
    department: '外科',
    doctorName: '李医生',
    appointmentDate: '2024-01-20',
    appointmentTime: '14:30',
    status: '待就诊',
    fee: 60,
    registrationNo: '20240120001',
    symptoms: '右腿疼痛',
    diagnosis: '待诊断',
    treatment: '待治疗'
  },
  {
    id: 'R003',
    patientName: '王*柯',
    department: '儿科',
    doctorName: '王医生',
    appointmentDate: '2024-01-25',
    appointmentTime: '10:00',
    status: '已取消',
    fee: 45,
    registrationNo: '20240125001',
    symptoms: '腹痛',
    diagnosis: '待诊断',
    treatment: '待治疗'
  }
]

const mockDoctorAdviceOrders = [
  {
    id: 'DA001',
    patientName: '王*柯',
    department: '内科',
    doctorName: '张医生',
    adviceDate: '2024-01-15',
    adviceType: '用药医嘱',
    status: '已完成',
    description: '感冒用药，每日三次，饭后服用',
    medicines: ['感冒灵颗粒', '维生素C片'],
    fee: 120,
    dosage: '感冒灵颗粒：每次1袋，每日3次；维生素C片：每次1片，每日3次',
    duration: '7天',
    notes: '多喝水，注意休息'
  },
  {
    id: 'DA002',
    patientName: '王*柯',
    department: '外科',
    doctorName: '李医生',
    adviceDate: '2024-01-20',
    adviceType: '检查医嘱',
    status: '待执行',
    description: '血常规检查，空腹12小时',
    medicines: [],
    fee: 80,
    preparation: '检查前12小时禁食',
    location: '检验科3楼',
    notes: '请携带身份证和检查单'
  },
  {
    id: 'DA003',
    patientName: '王*柯',
    department: '儿科',
    doctorName: '王医生',
    adviceDate: '2024-01-25',
    adviceType: '治疗医嘱',
    status: '执行中',
    description: '物理治疗，每日一次',
    medicines: [],
    fee: 200,
    treatmentPlan: '热敷治疗，每次20分钟',
    frequency: '每日1次',
    notes: '避免剧烈运动'
  }
]

// 异步thunk
export const fetchRegistrationOrders = createAsyncThunk(
  'orders/fetchRegistrationOrders',
  async () => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    return mockRegistrationOrders
  }
)

export const fetchDoctorAdviceOrders = createAsyncThunk(
  'orders/fetchDoctorAdviceOrders',
  async () => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    return mockDoctorAdviceOrders
  }
)

export const cancelRegistrationOrder = createAsyncThunk(
  'orders/cancelRegistrationOrder',
  async (orderId) => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    return orderId
  }
)

export const executeDoctorAdvice = createAsyncThunk(
  'orders/executeDoctorAdvice',
  async (orderId) => {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    return orderId
  }
)

// 初始状态
const initialState = {
  registrationOrders: [],
  doctorAdviceOrders: [],
  loading: false,
  error: null
}

// 创建slice
const ordersSlice = createSlice({
  name: 'orders',
  initialState,
  reducers: {
    // 添加新的挂号订单
    addRegistrationOrder: (state, action) => {
      state.registrationOrders.unshift(action.payload)
    },
    // 添加新的医嘱订单
    addDoctorAdviceOrder: (state, action) => {
      state.doctorAdviceOrders.unshift(action.payload)
    },
    // 更新挂号订单状态
    updateRegistrationOrderStatus: (state, action) => {
      const { orderId, status } = action.payload
      const order = state.registrationOrders.find(o => o.id === orderId)
      if (order) {
        order.status = status
      }
    },
    // 更新医嘱订单状态
    updateDoctorAdviceOrderStatus: (state, action) => {
      const { orderId, status } = action.payload
      const order = state.doctorAdviceOrders.find(o => o.id === orderId)
      if (order) {
        order.status = status
      }
    },
    // 清除错误
    clearError: (state) => {
      state.error = null
    }
  },
  extraReducers: (builder) => {
    builder
      // 获取挂号订单
      .addCase(fetchRegistrationOrders.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchRegistrationOrders.fulfilled, (state, action) => {
        state.loading = false
        state.registrationOrders = action.payload
      })
      .addCase(fetchRegistrationOrders.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message
      })
      // 获取医嘱订单
      .addCase(fetchDoctorAdviceOrders.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchDoctorAdviceOrders.fulfilled, (state, action) => {
        state.loading = false
        state.doctorAdviceOrders = action.payload
      })
      .addCase(fetchDoctorAdviceOrders.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message
      })
      // 取消挂号订单
      .addCase(cancelRegistrationOrder.fulfilled, (state, action) => {
        const order = state.registrationOrders.find(o => o.id === action.payload)
        if (order) {
          order.status = '已取消'
        }
      })
      // 执行医嘱
      .addCase(executeDoctorAdvice.fulfilled, (state, action) => {
        const order = state.doctorAdviceOrders.find(o => o.id === action.payload)
        if (order) {
          order.status = '执行中'
        }
      })
  }
})

// 导出actions
export const {
  addRegistrationOrder,
  addDoctorAdviceOrder,
  updateRegistrationOrderStatus,
  updateDoctorAdviceOrderStatus,
  clearError
} = ordersSlice.actions

// 导出selectors
export const selectRegistrationOrders = (state) => state.orders.registrationOrders
export const selectDoctorAdviceOrders = (state) => state.orders.doctorAdviceOrders
export const selectOrdersLoading = (state) => state.orders.loading
export const selectOrdersError = (state) => state.orders.error

// 导出reducer
export default ordersSlice.reducer
